package com.alogic.xscript.plugins;

import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsArray;
import com.alogic.xscript.doc.XsObject;
import com.alogic.xscript.doc.json.JsonArray;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;

/**
 * String形式的数组对象
 * 
 * @author yyduan
 * @since 1.6.11.28
 * 
 * @version 1.6.12.28 [20190407] <br>
 * - 优化对不同类型数据的支持 <br>
 *
 * @version 1.6.14.16 [20210816 duanyy] <br>
 * - 可通过分割符来加入多个array的成员 <br>
 */
public class ArrayString extends AbstractLogiclet {
	protected String id = "$array";
	protected String value = NULL;
	protected String dft = NULL;
	protected String type = "string";
	protected String delimiter = NULL;
	
	public ArrayString(String tag, Logiclet p) {
		super(tag, p);
	}

	@Override
	public void configure(Properties p){
		super.configure(p);
		id = PropertiesConstants.getString(p,"id",id,true);
		
		value = PropertiesConstants.getRaw(p,"value",value);
		type = PropertiesConstants.getString(p,"type",type,true);
		dft = PropertiesConstants.getRaw(p,"dft",dft);
		delimiter = PropertiesConstants.getString(p,"delimiter",NULL,true);
	}

	@Override
	protected void onExecute(XsObject root,XsObject current, LogicletContext ctx, ExecuteWatcher watcher) {
		XsArray list = ctx.getObject(id);
		if (list != null && list instanceof JsonArray){
			JsonArray jsonList = (JsonArray)list;
			String v = PropertiesConstants.transform(ctx, value, dft);
			if (StringUtils.isNotEmpty(v)){
				@SuppressWarnings("unchecked")
				List<Object> content = (List<Object>) jsonList.getContent();
				if (StringUtils.isNotEmpty(delimiter)){
					String [] items = v.split(delimiter);
					for (String item:items){
						switch (getType(type)) {
							case LONG:
								content.add(asTypeValue(item, 0));
								break;
							case INTEGER:
								content.add(asTypeValue(item, 0L));
								break;
							case DOUBLE:
								content.add(asTypeValue(item, 0.0d));
								break;
							case FLOAT:
								content.add(asTypeValue(item, 0.0f));
								break;
							case BOOLEAN:
								content.add(asTypeValue(item, false));
								break;
							default:
								content.add(item);
						}
					}
				}else {
					switch (getType(type)) {
						case LONG:
							content.add(asTypeValue(v, 0));
							break;
						case INTEGER:
							content.add(asTypeValue(v, 0L));
							break;
						case DOUBLE:
							content.add(asTypeValue(v, 0.0d));
							break;
						case FLOAT:
							content.add(asTypeValue(v, 0.0f));
							break;
						case BOOLEAN:
							content.add(asTypeValue(v, false));
							break;
						default:
							content.add(v);
					}
				}
			}
		}
	}	
}
